import React, { useState, useEffect } from 'react';
import axios from 'axios';

const AcademicOrganizationsForm = ({ applicationId }) => {
    const [academicOrganizations, setAcademicOrganizations] = useState([]);
    const [newAcademicOrganization, setNewAcademicOrganization] = useState({
        organizationName: '',
        position: '',
        startDate: '',
        endDate: '',
        remarks: ''
    });
    const [editingId, setEditingId] = useState(null);

    useEffect(() => {
        const fetchAcademicOrganizations = async () => {
            try {
                const response = await axios.get(`/api/applications/${applicationId}/academic-organizations`);
                setAcademicOrganizations(response.data);
            } catch (error) {
                console.error('Error fetching academic organizations:', error);
            }
        };

        if (applicationId) {
            fetchAcademicOrganizations();
        }
    }, [applicationId]);

    const handleChange = (e) => {
        const { name, value } = e.target;
        setNewAcademicOrganization(prevInfo => ({
            ...prevInfo,
            [name]: value
        }));
    };

    const handleAddOrUpdate = async (e) => {
        e.preventDefault();
        try {
            if (editingId) {
                await axios.put(`/api/applications/${applicationId}/academic-organizations/${editingId}`, newAcademicOrganization);
                alert('学术团体及任职情况更新成功！');
            } else {
                await axios.post(`/api/applications/${applicationId}/academic-organizations`, newAcademicOrganization);
                alert('学术团体及任职情况添加成功！');
            }
            setNewAcademicOrganization({
                organizationName: '',
                position: '',
                startDate: '',
                endDate: '',
                remarks: ''
            });
            setEditingId(null);
            const response = await axios.get(`/api/applications/${applicationId}/academic-organizations`);
            setAcademicOrganizations(response.data);
        } catch (error) {
            console.error('Error saving academic organization:', error);
            alert('保存失败，请重试。');
        }
    };

    const handleEdit = (info) => {
        setNewAcademicOrganization(info);
        setEditingId(info.id);
    };

    const handleDelete = async (id) => {
        try {
            await axios.delete(`/api/applications/${applicationId}/academic-organizations/${id}`);
            alert('学术团体及任职情况删除成功！');
            setAcademicOrganizations(academicOrganizations.filter(info => info.id !== id));
        } catch (error) {
            console.error('Error deleting academic organization:', error);
            alert('删除失败，请重试。');
        }
    };

    return (
        <div className="form-container">
            <h3>学术团体及任职情况</h3>
            <form onSubmit={handleAddOrUpdate}>
                <div className="form-group">
                    <label>组织名称:</label>
                    <input type="text" name="organizationName" value={newAcademicOrganization.organizationName} onChange={handleChange} required />
                </div>
                <div className="form-group">
                    <label>职务:</label>
                    <input type="text" name="position" value={newAcademicOrganization.position} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>开始日期:</label>
                    <input type="date" name="startDate" value={newAcademicOrganization.startDate} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>结束日期:</label>
                    <input type="date" name="endDate" value={newAcademicOrganization.endDate} onChange={handleChange} />
                </div>
                <div className="form-group">
                    <label>备注:</label>
                    <textarea name="remarks" value={newAcademicOrganization.remarks} onChange={handleChange}></textarea>
                </div>
                <button type="submit">{editingId ? '更新' : '添加'}</button>
            </form>

            <h4>已添加学术团体及任职情况</h4>
            <table>
                <thead>
                    <tr>
                        <th>组织名称</th>
                        <th>职务</th>
                        <th>开始日期</th>
                        <th>结束日期</th>
                        <th>备注</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {academicOrganizations.map(info => (
                        <tr key={info.id}>
                            <td>{info.organizationName}</td>
                            <td>{info.position}</td>
                            <td>{info.startDate}</td>
                            <td>{info.endDate}</td>
                            <td>{info.remarks}</td>
                            <td>
                                <button onClick={() => handleEdit(info)}>编辑</button>
                                <button onClick={() => handleDelete(info.id)}>删除</button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
};

export default AcademicOrganizationsForm;

